<?php

namespace App\Services;

use App\Common\Utils\Helper;
use App\Models\CommodityActivity;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\MorphToMany;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

class Commodity
{
    /**
     * 根据当前用户身份获取 sku 最低零售价 最低价格以及对应 赚的钱
     * @param $skuList
     * @return int[]
     */
    public static function getPriceFromSkuListByIdentity($skuList)
    {
        $currentIdentity = Auth::user()->currentLevelIdentity()['id'];

        $earn = 0;
        $price = 0;
        foreach ($skuList as $sku) {
            $currentPrice = $sku[$currentIdentity . '_price'] ?? 0;
            if (($price === 0) || $currentPrice < $price) {
                $price = $currentPrice;
                $earn = ($sku['external_guide_price'] ?? 0) - $price;
                $earn = $earn < 0 ? 0 : $earn;
            }
        }

        $externalGuidePrice = array_column($skuList, 'external_guide_price');
        return [$earn, $price, min(empty($externalGuidePrice) ? [0] : $externalGuidePrice)];
    }

    /**
     * 获取活动列表(缓存)
     * @param Request $request
     * @param null $type 允许单独控制 type
     * @return array|mixed
     */
    public static function getActivityListWithCache(Request $request, $type = null)
    {
        $searchName = $request->get('search_name', '');
        $page = $request->get('page', 1);
        $perPage = $request->get('per_page', 15);
//        Cache::tags('commodity_activity_list_cache')->flush();
        return Cache::tags('commodity_activity_list_cache')->remember(
            md5(implode(',', [$type, $searchName, $page, $perPage])),
            8 * 60 * 60,
            function () use ($type, $searchName) {
//                DB::enableQueryLog();
                $return = Helper::dealWithNotCompatibleSimplePaginate(
                    CommodityActivity::query()
                        ->with([
                            'attachments' => function (MorphToMany $morphToMany) {
                                $morphToMany
                                    ->select(['attachments.id', 'attachments.url', 'attachments.file'])
                                    ->wherePivot('type', CommodityActivity::ATTACHMENT_TYPE_MAIN_PIC);
                            },
                            'commodity:id,name',
                            'skus:id,commodity_activity_id,external_guide_price,stock',
                            'labels' => function (BelongsToMany $belongsToMany) {
                                $belongsToMany
                                    ->select(['commodity_labels.id', 'commodity_labels.name'])
                                    ->with(['attachments:attachments.id,attachments.url,attachments.file']);
                            }
                        ])
                        ->when($type, function (Builder $builder, $type) {
                            $builder->where('commodity_activities.type', $type);
                        })
                        ->when($searchName, function (Builder $builder, $searchName) {
                            $builder
                                ->join('commodities', 'commodities.id', '=', 'commodity_activities.commodity_id')
                                ->where('commodities.name', 'like', "%$searchName%");
                        })
                        ->panicBuyingTime()
                        ->putOnShelf()
                        ->select([
                            'commodity_activities.id',
                            'commodity_activities.name',
                            'commodity_activities.numbering',
                            'commodity_activities.status',
                            'commodity_activities.type',
                            'commodity_activities.panic_buying_start_time',
                            'commodity_activities.panic_buying_end_time',
                            'commodity_activities.commodity_id'
                        ])
                        ->simplePaginate()
                );
//                dd(DB::getQueryLog());
                return $return;
            });
    }

    /**
     * 清除活动列表系列缓存
     */
    public static function forgetCommodityActivityListCacheTag()
    {
        try {
            Cache::lock('forget_commodity_activity_list_cache_tag', 3)->block(3, function () {
                Cache::tags('commodity_activity_list_cache')->flush();
            });
        } catch (\Exception $e) {
            // 获取锁超时什么的 不用管
        }
    }

    /**
     * 获取活动详情缓存
     * @param $id
     * @return array|mixed
     */
    public static function getActivityInfoWithCache($id)
    {
        return Cache::tags('commodity_activity_list_cache')->remember(
            'activity_info_id_' . $id,
            8 * 60 * 60,
            function () use ($id) {
                return CommodityActivity::query()
                    ->select([
                        'commodity_activities.id',
                        'commodity_activities.name',
                        'commodity_activities.numbering',
                        'commodity_activities.desc',
                        'commodity_activities.freight',
                        'commodity_activities.panic_buying_end_time',
                        'commodity_activities.remote_regions_freight',
                        'commodity_activities.remote_regions_freight_setting',
                        'commodity_activities.commodity_id',
                        'commodity_activities.free_shipping_minimal',
                        'commodity_activities.free_shipping_maximum',
                    ])
                    ->with([
                        'materials' => fn (HasMany $hasMany) => $hasMany->select(['id', 'type', 'commodity_activity_id', 'content'])->with(['attachments:attachments.id,attachments.url,attachments.file']),
                        'attributes' => fn ($builder) => $builder->with(['values.attachments']),
                        'attachments:attachments.id,attachments.url,attachments.file',
                        'commodity' => fn (BelongsTo $belongsTo) => $belongsTo->select(['id', 'name'])->with(['attachments:attachments.id,attachments.url,attachments.file']),
                        'moments' => fn (HasMany $hasMany) => $hasMany->select(['id', 'commodity_activity_id', 'content'])->with(['attachments:attachments.id,attachments.url,attachments.file'])
                    ])
                    ->findOrFail($id)
                    ->toArray();
            }
        );
    }

    /**
     * 清理活动详情缓存
     * @param $id
     */
    public static function forgetCommodityActivityInfoCache($id)
    {
        Cache::tags('commodity_activity_list_cache')->forget('activity_info_id_' . $id);
    }
}
